// Copyright 2013 The golog2bq Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// +build appengine

package log2bq

import (
	"appengine"
	"compress/gzip"
	"fmt"
	"net/http"
	"strconv"
	"strings"
)

// Log2gsWorker is an HTTP request handler that will export logs to Google Cloud
// Storage.  Use the URL parameters "s" and "e" to specify a Unix time for the
// earliest and latest log records to export.  Use the URL parameter "bq" to
// optionally load the logs into BigQuery from Google Cloud Storage.  Use the
// URL parameter "v" to specify a comma separated list of major version IDs for
// the log query.
func Log2gsWorker(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	if globalLogger == nil {
		c.Errorf("Log2gsWorker: %v", ErrNilLogger)
		http.Error(w, ErrNilLogger.Error(), http.StatusInternalServerError)
		return
	}
	load2bq, _ := strconv.ParseBool(r.FormValue("bq"))
	vl := strings.Split(r.FormValue("v"), ",")
	q := newLogQuery(r.FormValue("s"), r.FormValue("e"), vl)
	fn, err := globalLogger.Log2gs(c, q)
	if err != nil {
		c.Errorf("Log2gsWorker:globalLogger.Log2gs: %v", err)
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	c.Infof("Log2gsWorker:globalLogger.Log2gs: %s", fn)
	if load2bq {
		err = globalLogger.Gs2bq(c, fn)
		if err != nil {
			c.Errorf("Log2gsWorker:globalLogger.Gs2bq: %v", err)
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
	}
	fmt.Fprint(w, fn)
}

// Log2bqWorker is an HTTP request handler that will export logs to BigQuery.
// Use the URL parameters "s" and "e" to specify a Unix time for the earliest
// and latest log records to export.  Use the URL parameter "v" to specify a
// comma separated list of major version IDs for the log query.
func Log2bqWorker(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	if globalLogger == nil {
		c.Errorf("Log2gsWorker: %v", ErrNilLogger)
		http.Error(w, ErrNilLogger.Error(), http.StatusInternalServerError)
		return
	}
	vl := strings.Split(r.FormValue("v"), ",")
	q := newLogQuery(r.FormValue("s"), r.FormValue("e"), vl)
	err := globalLogger.Log2bq(c, q)
	if err != nil {
		c.Errorf("Log2bqWorker:globalLogger.Log2bq: %v", err)
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	fmt.Fprintf(w, "OK")
}

// Log2CSV is an HTTP request handler that will export logs to a gziped csv
// download.  Use the URL parameters "s" and "e" to specify a Unix time for the
// earliest and latest log records to export.  Use the URL parameter "v" to
// specify a comma separated list of major version IDs for the log query.
func Log2CSV(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	vl := strings.Split(r.FormValue("v"), ",")
	q := newLogQuery(r.FormValue("s"), r.FormValue("e"), vl)
	gw := gzip.NewWriter(w)
	if q.StartTime.IsZero() {
		gw.Header.Name = fmt.Sprintf("%s.log.csv", appengine.AppID(c))
	} else {
		gw.Header.Name = fmt.Sprintf("%s_%d-%d.log.csv", appengine.AppID(c), q.StartTime.Unix(), q.EndTime.Unix())
	}
	w.Header().Set("Content-Type", "application/gzip; charset=utf-8")
	w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%s.gz", gw.Header.Name))

	err := log2csv(gw, c, q)
	if err != nil {
		c.Errorf("logs2CSVWorker:log2csv: %v", err)
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	err = gw.Close()
	if err != nil {
		c.Errorf("logs2CSVWorker:gw.Close: %v", err)
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
}
